package com.itheima.service.impl;

import com.itheima.dao.UserDao;
import com.itheima.domain.Order;
import com.itheima.domain.Product;
import com.itheima.domain.User;
import com.itheima.service.OrderService;
import com.itheima.service.ProductService;
import com.itheima.service.UserService;
import com.itheima.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private ProductService productService;
    @Autowired
    private OrderService orderService;

    //注入redisUtil
    @Autowired
    private RedisUtil redisUtil;

    //缓存键前缀（避免键冲突）
    private static final String USER_KEY_PREFIX = "user:";
    private static final String USER_STATS_PREFIX = "user:stats:";


    @Override
    public User findUserByName(String username) {
        //缓存键：uer：name:xxx
        String key = USER_KEY_PREFIX + "name:" + username;
        //1.先查看缓存
        User user = (User) redisUtil.get(key);
        if (user != null) {
            return user;
        }
        //2.缓存未命中，查数据库
        user = userDao.findByUsername(username);
        //3.存入缓存（设置过期时间30分钟，避免缓存雪崩）
        if (user != null) {
            redisUtil.set(key, user, 30, TimeUnit.MINUTES);
        }
        return user;
    }

    @Override
    public User userLogin(String username, String password) {
        // 根据用户名查询用户
        User user = userDao.findByUsername(username);

        // 用户不存在或密码不匹配
        if (user == null || !user.getPassword().equals(password)) {
            return null;
        }
        // 获取上一次登录时间（如果是第一次登录，lastLoginTime 可能为 null）
        Date lastLoginTime = user.getLastLoginTime();
        Date now = new Date();

        user.setLastLoginTime(lastLoginTime);
        userDao.updateLoginTime(user.getUserId(), now);

        //更新缓存中的用户信息（登陆时间变化）
        String idKey = USER_KEY_PREFIX + "id:" + user.getUserId();
        String nameKey = USER_KEY_PREFIX + "name:" + username;
        redisUtil.set(idKey, user, 30, TimeUnit.MINUTES);
        redisUtil.set(nameKey, user, 30, TimeUnit.MINUTES);

        return user; // 登录成功
    }

    @Override
    public User findUserById(int userId) {
        String key = USER_KEY_PREFIX + "id:" + userId;
        //1.先查缓存
        User user = (User) redisUtil.get(key);
        if (user != null) {
            return user;
        }
        user = userDao.findByUserId(userId);
        // 3. 存入缓存
        if (user != null) {
            redisUtil.set(key, user, 30, TimeUnit.MINUTES);
        }
        return user;
    }

    @Override
    public String userRegister(User user) {
        //验证用户名唯一性
        if (userDao.countByUsername(user.getUsername()) > 0) {
            return "用户名已存在！";
        }
        // 验证邮箱唯一性
        if (userDao.countByEmail(user.getEmail()) > 0) {
            return "邮箱已被注册！";
        }
        // 验证学号唯一性
        if (userDao.countByStudentId(user.getStudentId()) > 0) {
            return "学号已被注册！";
        }
        if (userDao.countByPhone(user.getPhone()) > 0) {
            return "手机号已被注册！";
        }
        Date nowTime = new Date();
        user.setRegisterTime(nowTime);
        // 插入用户
        return userDao.insertUser(user) > 0 ? null : "注册失败！";
    }

    @Override
    public String userUpdate(User user) {
        if (user == null) {
            return "信息不能为空！";
        }
        if (user.getUsername() == null || user.getEmail() == null || user.getStudentId() == null) {
            return "必填字段不能为空";
        }
        if (user.getUserId() == null) {
            return "用户ID不能为空";
        }
        if (userDao.countElseByUsername(user.getUsername(), user.getUserId()) > 0) {
            return "用户名已存在！";
        }
        // 验证邮箱唯一性
        if (userDao.countElseByEmail(user.getEmail(), user.getUserId()) > 0) {
            return "邮箱已被注册！";
        }
        // 验证学号唯一性
        if (userDao.countElseByStudentId(user.getStudentId(), user.getUserId()) > 0) {
            return "学号已被注册！";
        }
        if (userDao.countElseByPhone(user.getPhone(), user.getUserId()) > 0) {
            return "手机号已被注册！";
        }
        int updateRow = userDao.updateUser(user);
        if (updateRow > 0) {
            // 清除缓存（下次查询会自动加载新数据）
            String idKey = USER_KEY_PREFIX + "id:" + user.getUserId();
            String nameKey = USER_KEY_PREFIX + "name:" + user.getUsername();
            redisUtil.delete(idKey);
            redisUtil.delete(nameKey);
            return null;
        } else {
            return "信息修改失败，请重试！";
        }
    }

    @Override
    public boolean updateAvatar(Integer userId, String avatarPath) {
        try {
            // 1. 验证用户存在
            User user = userDao.findByUserId(userId);
            if (user == null) {
                throw new RuntimeException("用户不存在");
            }

            // 2. 更新头像路径
            userDao.updateAvatar(avatarPath, userId);


            // 更新缓存中的头像信息
            String idKey = USER_KEY_PREFIX + "id:" + userId;
            String nameKey = USER_KEY_PREFIX + "name:" + user.getUsername();
            user.setAvatar(avatarPath); // 更新对象属性
            redisUtil.set(idKey, user, 30, TimeUnit.MINUTES);
            redisUtil.set(nameKey, user, 30, TimeUnit.MINUTES);


            return true;
        } catch (Exception e) {
            // 记录日志
            System.err.println("更新头像失败: " + e.getMessage());
            throw new RuntimeException("更新头像失败", e);
        }
    }

    @Override
    public String selectRealNameById(int userId) {
        return userDao.getUserRealName(userId);
    }

    @Override
    public int setUserAddress(String address, int userId) {
        return userDao.updateAddress(address, userId);
    }

    @Override
    public int setUserPhone(String phone, int userId) {
        int rows = userDao.updatePhone(phone, userId);
        if (rows > 0) {
            // 更新手机号后清除缓存
            redisUtil.delete(USER_KEY_PREFIX + "id:" + userId);
        }
        return rows;
    }

    @Override
    public String getUserAvatar(int userId) {
        // 优先从缓存获取头像
        User user = (User) redisUtil.get(USER_KEY_PREFIX + "id:" + userId);
        if (user != null) {
            return user.getAvatar();
        }
        // 缓存未命中则查数据库
        return userDao.getUserAvatar(userId);
    }

    @Override
    public Map<String, Integer> getUserProductStats(Integer userId) {
        // 缓存键：user:stats:xxx
        String key = USER_STATS_PREFIX + userId;

        // 1. 先查缓存
        Map<String, Integer> stats = (Map<String, Integer>) redisUtil.get(key);
        if (stats != null) {
            return stats;
        }
        // 2. 缓存未命中，查数据库
        stats = new HashMap<>();
        // 1. 在售商品（status=1）
        List<Product> onsaleProducts = productService.findProductsByUserId(userId);
        onsaleProducts = onsaleProducts.stream()
                .filter(product -> product.getStatus() == 1)
                .collect(Collectors.toList());
        stats.put("onsale", onsaleProducts.size());

        // 2. 已售商品（通过订单查询）
        List<Order> soldOrders = orderService.findValidOrdersBySellerId(userId);
        List<Product> soldProducts = soldOrders.stream()
                .map(order -> {
                    Product product = productService.findProductById(order.getProductId());
                    if (product != null) {
                        product.setOrderId(order.getOrderId()); // 保持与查询逻辑一致
                    }
                    return product;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        stats.put("sold", soldProducts.size());

        // 3. 已购商品（通过订单查询）
        List<Order> purchasedOrders = orderService.findValidOrdersByBuyerId(userId);
        List<Product> purchasedProducts = purchasedOrders.stream()
                .map(order -> {
                    Product product = productService.findProductById(order.getProductId());
                    if (product != null) {
                        product.setOrderId(order.getOrderId()); // 保持与查询逻辑一致
                    }
                    return product;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        stats.put("purchased", purchasedProducts.size());

        // 4. 已下架商品（status=0）
        List<Product> removedProducts = productService.findProductsByUserId(userId);
        removedProducts = removedProducts.stream()
                .filter(product -> product.getStatus() == 0)
                .collect(Collectors.toList());
        stats.put("removed", removedProducts.size());
        // 3. 存入缓存（统计数据变化频率低，可设置1小时过期）
        redisUtil.set(key, stats, 1, TimeUnit.HOURS);
        return stats;
    }
}
